package multicast.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import multicast.server.messages.Messages;

public class MulticastServerThread extends Thread {
	
	private long ONE_SECOND = 1000;
	private String GROUP = "230.0.0.1";
	
	private DatagramSocket socket = null;
	
	public MulticastServerThread() throws SocketException {
		this.socket = new DatagramSocket(4445);
	}
	
	public void run() {
		
		int curr_message = 0;
		int max_message = Messages.messages.size();
		
		while (true) {

			String message =(String)  Messages.messages.get(curr_message); 

			System.out.println("Enviando pacote para " + GROUP + ": " + message);

			byte[] msg = message.getBytes();
			
			try {
		        InetAddress group = InetAddress.getByName(GROUP);
		        DatagramPacket packet = new DatagramPacket(msg, msg.length, group, 4446);            
				socket.send(packet);
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage());
			}
			
			try {
			    sleep((long)(ONE_SECOND));
			} catch (InterruptedException e) { }
			
			curr_message = (curr_message +1) % max_message;
		}
	}
}
